package com.wisely.ch8_5.repository;

import com.wisely.ch8_5.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@Repository
public class PersonDao implements IPersonDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public Person insert(Person person) {
        jdbcTemplate.update("insert into person (id,name,age) VALUE (?,?,?)",person.getId(),person.getName(), person.getAge());
        return person;
    }

    @Override
    public void delete(Long id) {
        jdbcTemplate.update("delete from person WHERE id = ?",id);
    }

    @Override
    public Person findOne(Long id) {
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(id);
        return jdbcTemplate.queryForObject("select * from person where id = ?",new PersonRowMapper(), objects.toArray());
    }
}

class PersonRowMapper implements RowMapper<Person> {

    @Override
    public Person mapRow(ResultSet resultSet, int rowNum) throws SQLException {
        Person person = new Person();
        person.setId((long) resultSet.getInt("id"));
        person.setName(resultSet.getString("name"));
        person.setAge(resultSet.getInt("age"));
        return person;
    }
}
